package providers

import (
	"fmt"
	"time"

	"github.com/streadway/amqp"
)

/**
 * 新建 rabbitmq 连接
 */
func NewRabbitmq(region string) (*amqp.Connection, *amqp.Channel) {
	var err error
	//判断是否有区域
	mqConfig := ""
	if region == "" {
		mqConfig = "rabbitmq"
	} else {
		mqConfig = "rabbitmq." + region
	}

	rabbitMqConfig := Config.GetStringMapString(mqConfig)

	//"amqp://guest:guest@localhost:5672/"
	login := fmt.Sprintf(
		"amqp://%s:%s@%s:%s/",
		rabbitMqConfig["user"],
		rabbitMqConfig["password"],
		rabbitMqConfig["host"],
		rabbitMqConfig["port"],
	)

	Logger.Debugf("rabbitmq 初始化:%s,config:%+v---%s----%s", login, rabbitMqConfig, mqConfig, region)

	// 获取 rabbitmq 的连接
	config := amqp.Config{
		Vhost:     rabbitMqConfig["vhost"],
		Heartbeat: 1 * time.Minute, // 心跳设置为 1 分钟
	}
	rabbitmq, err := amqp.DialConfig(login, config)
	if err != nil {
		Logger.Errorf("rabbitmq 连接有误:%s", err.Error())
		panic("rabbitmq 连接有误:" + err.Error())
	}

	rabbitmqChannel, err := rabbitmq.Channel()
	if err != nil {
		Logger.Errorf("rabbimq channel 创建有误:%s", err.Error())
		panic("rabbimq channel 创建有误:" + err.Error())
	}

	return rabbitmq, rabbitmqChannel
}
